package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.StrategyTheme;
import cn.wolfcode.luowowo.query.StrategyThemeQuery;
import cn.wolfcode.luowowo.repository.StrategyThemeRepository;
import cn.wolfcode.luowowo.service.IStrategyThemeService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class StrategyThemeServiceImpl implements IStrategyThemeService{
    @Autowired
    private StrategyThemeRepository strategyThemeRepository;
    @Autowired
    private MongoTemplate template;
    @Override
    public List<StrategyTheme> list() {

        return strategyThemeRepository.findAll();
    }

    @Override
    public Page<StrategyTheme> query(StrategyThemeQuery qo) {
        //条件
        Query query = new Query();
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, "_id");
        return DBHelper.query(template,StrategyTheme.class,query,pageable);
    }

    @Override
    public void saveOrUpdate(StrategyTheme strategyTheme) {
        if(!StringUtils.hasLength(strategyTheme.getId())){
            strategyTheme.setId(null);
            strategyThemeRepository.save(strategyTheme);
        }else {
            //注意: MongoDB的更新是全量更新,所以操作是先查 再替换 再更新
            //但此时无需注意其他数据,因为刚好页面传过来的参数是与数据库中列的个数是一样的,
            //当后续还有其他情况时则再看,
            strategyThemeRepository.save(strategyTheme);
        }
    }

    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);
        strategyThemeRepository.save(strategyTheme);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        strategyThemeRepository.save(strategyTheme);
    }


    @Override
    public void delete(String id) {
        strategyThemeRepository.deleteById(id);
    }

    @Override
    public StrategyTheme get(String rid) {
        /*Optional<StrategyTheme> optional = strategyThemeRepository.findById(rid);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;*/
        return strategyThemeRepository.findById(rid).orElse(null);
    }



}
